package org.techmore.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class InitailDatabase {
	
	public static InitailDatabase getInstance(){
		return new InitailDatabase();
	}
	
	private SQLiteDatabase sqLiteDatabase = null;
	private Properties properties = null;
	
	public void initDB(Context context){
		initProperties();
		String name = PropertiesUtil.getInstance().getValue("databaseName");
		if(!context.getDatabasePath(name).exists()){
			sqLiteDatabase = new DatabaseHelper(context, name).getWritableDatabase();
			try {
				sqLiteDatabase.beginTransaction();
				for(Map.Entry<Object, Object> me : properties.entrySet()){
					if(me.getKey().toString().endsWith("_create")){
//						System.out.println(me.getValue().toString());
						sqLiteDatabase.execSQL(me.getValue().toString());
					}
				}
				sqLiteDatabase.setTransactionSuccessful();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				sqLiteDatabase.endTransaction();
				sqLiteDatabase.close();
			}
		}
		
	}
	
	public void initProperties(){
		properties = new Properties();
		try {
			properties.load(InitailDatabase.class.getClassLoader().getResourceAsStream("sqlite.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
